package com.thank.concurrency.samples.atomic;

import com.thank.concurrency.annoations.ThreadSafe;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author thank
 * 演示AtomicIntegerFieldUpdater
 */
@Slf4j
@ThreadSafe
public class AtomicExample5 {

    // 该属性的限制: 必须是volatile, 非static
    @Getter
    private volatile int count = 100;

    /**
     * AtomicIntegerFieldUpdater 核心是原子性的去更新一个类的实例的指定字段
     * newUpdater构造函数第一个参数为类定义，第二个参数为指定字段的属性名，必须是volatile修饰并且非static的字段
     */
    private static AtomicIntegerFieldUpdater<AtomicExample5> updater
            = AtomicIntegerFieldUpdater.newUpdater(AtomicExample5.class, "count");

    public static void main(String[] args) {
      AtomicExample5 example5 = new AtomicExample5();
      if (updater.compareAndSet(example5, 100, 200)) {
         log.info("update1 success, count = {}", example5.getCount());
      }

        if (updater.compareAndSet(example5, 100, 300)) {
            log.info("update2 success, count = {}", example5.getCount());
        } else {
            log.info("update2 failed, count = {}", example5.getCount());
        }
    }
}
